package com.xinyue.game.web.gateway.access;

import com.alibaba.fastjson.JSONObject;
import com.xinyue.game.jwt.GameJwtService;
import com.xinyue.game.jwt.GameUserToken;
import com.xinyue.game.jwt.JwtTokenErrorException;
import com.xinyue.game.jwt.JwtTokenExpiredException;
import com.xinyue.game.web.gateway.common.XinYueWebGatewaySystemConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.netty.ByteBufFlux;

import java.nio.charset.StandardCharsets;

/**
 * 访问授权过滤器，如果访问的地址，不在忽略名单内，则必须经过授权检测才可以访问
 *
 * @author 王广帅
 * @since 2023/5/23 21:12
 **/
@Service
public class AccessAuthVerifyFilter implements GlobalFilter {

    private Logger logger = LoggerFactory.getLogger(AccessAuthVerifyFilter.class);
    @Autowired
    private XinYueWebGatewaySystemConfig webGatewaySystemConfig;


    private GameJwtService gameJwtService = new GameJwtService();


    private boolean isIgnoreCheckUri(String uri) {
        return webGatewaySystemConfig.getUriAuthIgnoreList().contains(uri);
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String userToken = exchange.getRequest().getHeaders().getFirst("Authorization-Token");
        String uri = exchange.getRequest().getPath().value();
        logger.debug("收到请求：{}", uri);
        if (ObjectUtils.isEmpty(userToken)) {
            if (isIgnoreCheckUri(uri)) {
                // 如果是不需要检测的请求，直接返回成功
                return chain.filter(exchange);
            } else {
                return this.responseError(exchange, 5001, "未登陆成功，请重新登陆之后再重试");
            }
        } else {
            byte[] key = webGatewaySystemConfig.getTokenAesKey().getBytes(StandardCharsets.UTF_8);
            try {
                GameUserToken gameRoleToken = gameJwtService.checkTokenAndGet(userToken, key, GameUserToken.class);
                if (gameRoleToken == null || gameRoleToken.getUserId() == null) {
                    return this.responseError(exchange, 5001, "登陆数据不正确，请重新登陆");
                }
            } catch (JwtTokenExpiredException e) {
                return this.responseError(exchange, 5002, "登陆已过期，请重新登陆");
            } catch (JwtTokenErrorException e) {
                return this.responseError(exchange, 5003, "非法登陆，请重新登陆");
            }
        }
        // 如果没有异常，继续往下传递
        return chain.filter(exchange);
    }

    /**
     * 统一响应错误提示
     *
     * @param exchange
     * @param code
     * @param msg
     * @return
     */
    private Mono<Void> responseError(ServerWebExchange exchange, int code, String msg) {
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.OK);
        JSONObject data = new JSONObject();
        data.put("code", code);
        data.put("data", msg);
        String dataStr = data.toJSONString();
        byte[] dataBytes = dataStr.getBytes(StandardCharsets.UTF_8);
        Mono<Void> ret = response.writeAndFlushWith(Flux.just(ByteBufFlux.just(response.bufferFactory().wrap(dataBytes))));
        logger.debug("请求失败：{}", dataStr);
        return ret;
    }
}
